package org.jeecg.modules.netty.handler.lamp;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.corp.netty.CloudBoxPackageContainer;
import org.jeecg.modules.corp.netty.LampPackageContainer;
import org.jeecg.modules.corp.netty.NettyChannelContainer;
import org.jeecg.modules.corp.netty.cloudbox.HeartPkg;
import org.jeecg.modules.corp.netty.cloudbox.PackageConstant;
import org.jeecg.modules.corp.netty.cloudbox.RegisPkg;
import org.jeecg.modules.corp.netty.cloudbox.StatusChangePkg;
import org.jeecg.modules.corp.netty.lamp.LampAA55FramePkg;
import org.jeecg.modules.corp.netty.lamp.LampFrameContent;
import org.jeecg.modules.corp.netty.lamp.LampQueryComm;
import org.jeecg.modules.netty.CRC16Util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
public class AA55FrameExec {


    /**
     *
     * @param ctx
     * @param pkg
     */
    public static void execData(ChannelHandlerContext ctx, LampAA55FramePkg pkg) throws JsonProcessingException {
        if(pkg==null){
            return;
        }
        short funCode = pkg.getFunCode();
        if(LampFrameContent.REG_FUN_CODE==funCode){
            execHeart(ctx,pkg);
        }else {

        }

        //LampPackageContainer.putPackage(pkg);

    }

    /**
     * 注册包/心跳包处理
     * @param ctx
     * @param pkg
     */
    private static void execHeart(ChannelHandlerContext ctx, LampAA55FramePkg pkg){
        log.info("收到注册/心跳包");
        Map<String,Number> pMap = pkg.getPMap();
        if(pMap ==null|| pMap.isEmpty()){
            return;
        }
        Long imei = pMap.get(LampFrameContent.IMEI)==null?null:pMap.get(LampFrameContent.IMEI).longValue();
        if(imei==null){
            return;
        }
        String imeiStr = Long.toHexString(imei);
        ctx.channel().attr(LampFrameContent.IMEI_ATTR).setIfAbsent(imeiStr);
        NettyChannelContainer.add(imeiStr,ctx.channel());

        LampQueryComm comm = new LampQueryComm();
        comm.setMagic(LampFrameContent.QUERY_ONE_MAGIC);
        comm.setDeviceAddr((int) pkg.getDeviceAddr());
        List<Number> contentList = new ArrayList<>();
        contentList.add((byte)0xFF);
        comm.setContentList(contentList);
        ctx.writeAndFlush(comm);

    }



}
